/**
 * 
 */
package com.seguriapp.sync;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.seguriapp.R;
import com.seguriapp.communication.WebServiceConsumer;
import com.seguriapp.entities.SignalEntity;

/**
 * @author pjohnson
 * 
 */
public class SignalTask extends AsyncTask<Object, Boolean, Boolean> {

	private Context mContext;
	private SignalEntity mSignal;
	private ProgressDialog mDialog;

	public SignalTask(final Context context, final SignalEntity signal) {
		mContext = context;
		mSignal = signal;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		mDialog = ProgressDialog.show(mContext, "Alerta", "Enviando Alerta...");
	}

	@Override
	protected Boolean doInBackground(Object... arg0) {
		boolean rptaBool = false;
		final WebServiceConsumer webServiceConsumer = WebServiceConsumer
				.getInstance(mContext);
		final JSONObject jsonSignal = new JSONObject();
		try {
			jsonSignal.put("latitude", mSignal.getLatitude());
			jsonSignal.put("longitude", mSignal.getLongitude());
			jsonSignal.put("names", mSignal.getName());
			jsonSignal.put("lastNames", mSignal.getLastName());
			jsonSignal.put("phone", mSignal.getPhone());
			jsonSignal.put("dni", mSignal.getDni());
			jsonSignal.put("date", mSignal.getDate());
			jsonSignal.put("postalCode", mSignal.getPostalCode());
		} catch (final JSONException e) {
			Log.e("Error Json", e.getMessage());
		}

		final String rpta = webServiceConsumer.sendSignal(jsonSignal);
		if (rpta.contains("true")) {
			rptaBool = true;
		}
		return rptaBool;
	}

	@Override
	protected void onPostExecute(final Boolean result) {
		mDialog.dismiss();
		if (result) {
			Toast.makeText(mContext,
					mContext.getString(R.string.msg_success_alert),
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(mContext,
					mContext.getString(R.string.msg_fail_alert),
					Toast.LENGTH_SHORT).show();
		}

	}
}
